<template>
    <div class="login-log-container">
        <!-- 岗位管理 -->
        <!-- 表单搜索项 -->
        <el-form v-if="showSearch" :model="params">
            <el-row :gutter="20">
                <el-col :span="5">
                    <el-form-item label="岗位编码" :class="{ 'bold-label': true }">
                        <el-input v-model="params.postCode" placeholder="请输入岗位编码" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="岗位名称" :class="{ 'bold-label': true }">
                        <el-input v-model="params.postName" placeholder="请输入岗位名称" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="状态" :class="{ 'bold-label': true }">
                        <el-select v-model="params.status" placeholder="岗位状态" clearable @change="handleStatusChange">
                            <el-option label="正常" value="0" />
                            <el-option label="停用" value="1" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
                    <el-button plain :icon="Refresh" @click="handleReset">重置</el-button>
                </el-col>
            </el-row>
        </el-form>
        <!-- 按钮组 -->
        <el-row class="button-group">
            <el-col :span="10">
                <div>
                    <el-button type="primary" :icon="Plus" plain @click=handleadd>新增</el-button>
                    <el-button type="success" plain :disabled="isSingleRowSelected" :icon="EditPen"
                        @click="PostUpdateId">修改</el-button>
                    <el-button type="danger" plain :disabled="deleteDisabled" :icon="Delete"
                        @click="handleDeleteIds">删除</el-button>
                    <el-button type="warning" plain :icon="Download">导出</el-button>
                </div>
            </el-col>
            <el-col :span="14">
                <div class="button-right">
                    <el-tooltip content="隐藏搜索" placement="top">
                        <el-button :icon="Search" circle @click="toggleSearch" />
                    </el-tooltip>
                    <el-tooltip content="刷新" placement="top">
                        <el-button :icon="Refresh" circle @click="Reload" />
                    </el-tooltip>
                </div>
            </el-col>
        </el-row>
        <!-- 数据表格 -->
        <el-row>
            <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" :selectable="selectable" width="40" />
                <el-table-column prop="postId" label="岗位编号" align="center" />
                <el-table-column prop="postCode" label="岗位编码" align="center" />
                <el-table-column prop="postName" label="岗位名称" align="center" />
                <el-table-column prop="postSort" label="岗位排序" align="center" />
                <el-table-column prop="status" label="岗位状态" align="center">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === '0' ? 'primary' : 'danger'">
                            {{ scope.row.status === '0' ? '正常' : '停用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" sortable align="center" width="180" />

                <el-table-column width="253px" label="操作" align="center">
                    <template #default="scope">
                        <el-button class="btn_m" plain type="primary" text size="small" :icon="EditPen"
                            @click="handleupdate(scope.$index, scope.row)">修改</el-button>
                        <el-button class="btn_m" plain type="primary" text size="small" :icon="Delete"
                            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-row>
        <!-- 分页组件 -->
        <el-row>
            <el-col :span="24">
                <div class="demo-pagination-block">
                    <el-pagination :current-page="params.currentPage" :page-size="params.pageSize" background
                        :default-page-size="params.pageSize" :page-sizes="pageSizes"
                        layout="total,sizes,prev,pager,next,jumper" :total="pageResult.total"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange">
                    </el-pagination>
                </div>
            </el-col>
        </el-row>

        <!-- 弹窗显示 -->
        <el-dialog v-model="dialogVisible" :title="title" draggable width="40%" @close="handleClose" class="dialogs"
            @open="handleOpenDialog">
            <el-form :model="posts" ref="postsFrom" :rules="postsRules" label-width="100px">
                <el-row>
                    <el-col>
                        <el-form-item label="岗位名称" :class="{ 'bold-label': true }" prop="postName">
                            <el-input v-model="posts.postName" placeholder="请输入岗位名称" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item label="岗位编码" :class="{ 'bold-label': true }" prop="postCode">
                            <el-input v-model="posts.postCode" placeholder="请输入岗位编码" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col class="sort-col">
                        <el-form-item label="岗位排序" :class="{ 'bold-label': true }" prop="postSort">
                            <el-input-number v-model="posts.postSort" :min="0" controls-position="right">
                                <template #input>
                                    <span v-if="posts.postSort !== 0">{{ posts.postSort }}</span>
                                </template>
                            </el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col class="status-col">
                        <el-form-item label="岗位状态" :class="{ 'bold-label': true }">
                            <el-radio-group v-model="posts.status">
                                <el-radio value="0">正常</el-radio>
                                <el-radio value="1">停用</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注" :class="{ 'bold-label': true }">
                            <el-input v-model="posts.remark" placeholder="请输入内容" :rows="2" type="textarea"
                                clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="handleSubmit(postsFrom)">确定</el-button>
                    <el-button @click="dialogVisible = false">取消</el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>

<script setup>
import { deletePostIds, insertPost, updatePost, findBySys_postId } from '@/apis/lth/index'
import { nextTick, onMounted, reactive, ref } from 'vue';
import { Search, Refresh, Delete, Download, Plus, EditPen } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPostList } from '@/apis/lth';

const tableData = ref([])   // 表格数据
const pageResult = ref({}) // 分页数据
let ids = ref([]) // 选中行的id数组
let postVal = ref([]) //选中行
const deleteDisabled = ref(true) // 删除按钮禁用状态,默认禁用
const isSingleRowSelected = ref(true) // 修改按钮禁用状态,默认禁用
const dialogVisible = ref(false) // 弹窗显示
const title = ref('') // 弹窗标题

// 搜索参数
const params = ref({
    currentPage: 1,
    pageSize: 10,
    postCode: '',
    postName: '',
    status: ''
})

// 传输数据
const posts = ref({
    postCode: '',
    postName: '',
    postId: undefined,
    postSort: 0,
    status: '0',
    remark: ""
})
// 分页大小
const pageSizes = [10, 20, 30, 40, 50]

onMounted(async () => {
    // 加载岗位列表数据
    await getPostList(params.value).then(res => {
        pageResult.value = res
        tableData.value = pageResult.value.records
    })
})
//刷新数据
const loadList = () => {
    getPostList(params.value).then(res => {
        pageResult.value = res
        tableData.value = pageResult.value.records || []
        if (!pageResult.value.total) {
            pageResult.value.total = 0
        }
    })
}
/**
 * 更新状态
 * @param value 状态值
 */
const handleStatusChange = (value) => {
    params.value.status = value
}
/**
 * 处理搜索
 * @param params 搜索参数
 */
const handleSearch = async () => {
    loadList();
}
/**
 * 处理重置
 * @param params 搜索参数
 */
const handleReset = async () => {
    params.value = {
        currentPage: 1,
        pageSize: 10,
        postCode: '',
        postName: '',
        status: ''
    }
    loadList();
}
/**
 * 处理分页大小变化
 * @param size 当前分页大小
 */
const handleSizeChange = async (size) => {
    params.value.pageSize = size
    loadList();
}
/**
 * 处理当前页码变化
 * @param currentPage 当前页码
 */
const handleCurrentChange = async (currentPage) => {
    params.value.currentPage = currentPage
    loadList();
}

//隐藏搜索条件
const showSearch = ref(true);
const toggleSearch = () => {
    showSearch.value = !showSearch.value;
}
//刷新
const Reload = () => {
    loadList();
}

/**
 * 自定义删除选中行的处理方法
 * @param row 行数据
 */
const selectable = (row) => {
    // 表示所有行数据都可以被选中，可以自定义选择逻辑
    return true
}
/**
 * 处理选中行变化
 * @param val 选中行的数组
 */
const handleSelectionChange = (val) => {
    console.log(val)
    deleteDisabled.value = !val.length
    ids.value = val.map(item => item.postId) // 使用map方法过滤出选中行的postId数组
    postVal.value = val.map(item => item); // 存储选中行的完整数据
    console.log(postVal.value)
    isSingleRowSelected.value = !(val.length === 1); // 如果只有一个选中行，则启用修改按钮
    if (!isSingleRowSelected.value) {
        posts.value = { ...val[0] } //将选中要修改的数据存储起来
    }
}
/**
 * 处理删除选中行
 * @param ids 选中行的id数组
 */
const handleDeleteIds = () => {
    ElMessageBox.confirm(`是否确认删除访问编号为${ids.value.join(',')}的数据项？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        let shouldContinue = true;
        for (let i = 0; i < ids.value.length && shouldContinue; i++) {
            const id = ids.value[i];
            const count = await findBySys_postId([id]);
            if (count > 0) {
                //找到已分配的岗位
                const post = postVal.value.find(item => item.postId === id);
                if (post) {
                    ElMessage.error(`${post.postName}已分配，不能删除`);
                    shouldContinue = false;// 停止进一步的删除操作
                    break;//结束循环
                }
            }
        }
        if (shouldContinue) {
            // 如果没有已分配的岗位，执行删除操作
            await deletePostIds(ids.value)
            loadList();
            ElMessage({ type: 'success', message: '删除成功' });
            // 重新加载选中状态
            const selectedPosts = postVal.value.find(item => ids.value.includes(item.postId));
            ids.value = selectedPosts.map(item => item.postId);
        }

    })
}
/**
 * 删除岗位（根据id）
 * @param index 行索引
 * @param row 行数据
 */
const handleDelete = async (index, row) => {
    ElMessageBox.confirm(`是否确认删除岗位编号为${row.postId}的数据项？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        ids.value.length = 0;
        ids.value.push(row.postId);
        const count = await findBySys_postId(ids.value);
        if (count > 0) {
            ElMessage.error(`${row.postName}已分配，不能删除`);
            ids.value = [];
            return;
        }
        await deletePostIds(ids.value);
        loadList();
        ElMessage.success("删除成功");
    })
}

const postsFrom = ref();
const frompost = reactive({ ...posts });
const postsRules = {//验证规则对象
    postName: [{
        required: true,//必填项
        message: "岗位名称不能为空",//提示错误信息
        trigger: "blur"
    }],
    postCode: [{ required: true, message: "岗位编码不能为空", trigger: "blur" }],
    postSort: [{ required: true, message: "岗位顺序不能为空", trigger: "blur" }]
};
const handleOpenDialog = () => {//打开对话框的处理函数
    nextTick(() => {
        postsFrom.value.clearValidate();//清空校验（清空表单校验结果，以便用户重新输入数据）
    })
}

/**
 * 修改岗位弹窗显示层(选中的行)
 */
const PostUpdateId = () => {
    title.value = '修改岗位'
    dialogVisible.value = true
}
/**
 * 修改岗位弹窗显示层
 * @param index 行索引
 * @param row 行数据
 */
const handleupdate = (index, row) => {
    title.value = '修改岗位'
    dialogVisible.value = true
    posts.value.postId = row.postId
    posts.value.postCode = row.postCode
    posts.value.postName = row.postName
    posts.value.postSort = row.postSort
    posts.value.status = row.status == '0' ? "0" : "1"
    posts.value.remark = row.remark
}
/**
 * 新增岗位弹窗显示层
 * @param index 
 */
const handleadd = (index) => {
    title.value = '添加岗位',
        posts.value = {
            postCode: '',
            postName: '',
            postId: undefined,
            postSort: 0,
            status: "0",
            remark: ""
        }
    dialogVisible.value = true
}
/**
 * 添加岗位，数据提交
 */
const handleSubmit = async (value) => {
    if (!value) return;
    await value.validate(valid => {
        if (valid) {
            if (title.value == '添加岗位') {
                insertPost(posts.value).then(res => {
                    if (res == "成功") {
                        ElMessage.success("新增成功")
                    } else {
                        ElMessage.error("新增失败")
                    }
                })
            } else {
                updatePost(posts.value).then(res => {
                    if (res == "成功") {
                        ElMessage.success("修改成功")
                    } else {
                        ElMessage.error("修改失败")
                    }
                })
            }
            dialogVisible.value = false;
            handleClose();
        } else {// ElMessage.error("请根据提示完整表单数据！");
            console.log("请根据提示完整表单数据！");
        }
    })
}

/**
 * 关闭弹窗,处理数据
 */
const handleClose = async () => {
    if (title.value == '添加岗位') {
        resetData()
    }
    loadList();
}
/**
 * 重置数据
 */
function resetData() {
    posts.value = {
        postCode: '',
        postName: '',
        postId: undefined,
        postSort: 0,
        status: "0",
        remark: ""
    }
    title.value = ''
}

</script>

<style scoped>
::v-deep .el-dialog {
    padding: 30px 20px
}

.dividing-line {
    text-align: center;
}

.button-right {
    text-align: right;
}

.button-group {
    margin-top: 20px;
    margin-bottom: 10px;
}

.demo-pagination-block .el-pagination {
    justify-content: end;
    margin-top: 20px;
}

/* 使用 ::v-deep 选择器 */
::v-deep .el-table .el-table__header-wrapper thead tr th {
    background-color: #f8f8f9 !important;
    /* 你可以根据需要更改颜色 */
    color: #515a6e !important;
    /* 文字颜色 */
}

/* 如果需要更具体的控制，可以使用更详细的类名 */
::v-deep .el-table .el-table__header-wrapper thead tr th,
::v-deep .el-table .el-table__body-wrapper tbody tr td {
    padding-left: 0 !important;
    /* 移除左边距 */
}

/* 使用 ::v-deep 选择器来穿透作用域样式 */
::v-deep.el-table th,
::v-deep .el-table td {
    padding-left: 0 !important;
    /* 移除左边距 */
}

::v-deep .bold-label .el-form-item__label {
    font-weight: bold !important;
}
</style>
